package com.ruoyi.erp.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.erp.domain.GlAccvouch;
import com.ruoyi.erp.service.IGlAccvouchService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.erp.domain.LedyAccass;
import com.ruoyi.erp.service.ILedyAccassService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 凭证现金流量Controller
 *
 * @author ruoyi
 * @date 2024-03-19
 */
@RestController
@RequestMapping("/erp/accass")
public class LedyAccassController extends BaseController {
    @Autowired
    private ILedyAccassService ledyAccassService;
    @Autowired
    private IGlAccvouchService glAccvouchService;

    /**
     * 查询凭证现金流量列表
     */
    @PreAuthorize("@ss.hasPermi('erp:accass:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedyAccass ledyAccass) {
        startPage();
        List<LedyAccass> list = ledyAccassService.selectLedyAccassList(ledyAccass);
        return getDataTable(list);
    }

    /**
     * 导出凭证现金流量列表
     */
    @PreAuthorize("@ss.hasPermi('erp:accass:export')")
    @Log(title = "凭证现金流量", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, LedyAccass ledyAccass) {
        List<LedyAccass> list = ledyAccassService.selectLedyAccassList(ledyAccass);
        ExcelUtil<LedyAccass> util = new ExcelUtil<LedyAccass>(LedyAccass.class);
        util.exportExcel(response, list, "凭证现金流量数据");
    }

    /**
     * 获取凭证现金流量详细信息
     */
    @PreAuthorize("@ss.hasPermi('erp:accass:query')")
    @GetMapping(value = "/{ccusId}")
    public AjaxResult getInfo(@PathVariable("ccusId") String ccusId) {
        return success(ledyAccassService.selectLedyAccassByCcusId(ccusId));
    }

    /**
     * 新增凭证现金流量
     */
    @PreAuthorize("@ss.hasPermi('erp:accass:add')")
    @Log(title = "凭证现金流量", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedyAccass ledyAccass) {
        return toAjax(ledyAccassService.insertLedyAccass(ledyAccass));
    }

    /**
     * 修改凭证现金流量
     */
    @PreAuthorize("@ss.hasPermi('erp:accass:edit')")
    @Log(title = "凭证现金流量", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedyAccass ledyAccass) {
        List<LedyAccass> list = ledyAccassService.selectLedyAccassList(ledyAccass);
        GlAccvouch accvouch = new GlAccvouch();
        accvouch.setCbill("张洋");
        accvouch.setCsign("记");
        accvouch.setIsignseq("1");
        accvouch.setCname("-");
        accvouch.setIdoc("-1");
        accvouch.setDbillDate(ledyAccass.getDbillDate() != null ? ledyAccass.getDbillDate() : DateUtil.parse(DateUtil.today()));
        accvouch.setiYear(DateUtil.year(accvouch.getDbillDate()) + "");
        accvouch.setIperiod((DateUtil.month(accvouch.getDbillDate()) + 1) + "");
        accvouch.setiYPeriod(DateUtil.format(accvouch.getDbillDate(), "yyyyMM"));
        GlAccvouch accvouchQuery = new GlAccvouch();
        accvouchQuery.setiYPeriod(accvouch.getiYPeriod());
        GlAccvouch accvouchQueryReturn = glAccvouchService.selectGlAccvouchMaxId(accvouchQuery);
        AtomicInteger noId = new AtomicInteger(1);
        if (accvouchQueryReturn != null && accvouchQueryReturn.getInoId() != null)
            noId.set(accvouchQueryReturn.getInoId());//当前年月最大编号
        AtomicInteger mNum = new AtomicInteger(0);
        String[] strNum = new String[500];
        AtomicInteger inid = new AtomicInteger(0);
        list.forEach(item -> {
            if (StringUtils.isBlank(item.getAcceptNumber()) || item.getAcceptNumber().equalsIgnoreCase("NULL")) {
                item.setAcceptNumber(item.getCcusId());
            }
            if (!Arrays.asList(strNum).contains(item.getAcceptNumber())) {
                if (mNum.getAndIncrement() % ledyAccass.getmNum() == 0) {
                    accvouch.setInoId(noId.incrementAndGet());
                    inid.set(0);
                }
                mNum.getAndIncrement();
                strNum[mNum.get()] = item.getAcceptNumber();
//                inid[0] = 0;
            } else {
                return;
            }
            List<LedyAccass> listM = new ArrayList<>();
            AtomicReference<Double> sumMd = new AtomicReference<>((double) 0);
            AtomicReference<Double> sumMc = new AtomicReference<>((double) 0);
            list.forEach(itemM -> {
                if (StringUtils.isBlank(itemM.getAcceptNumber()) || itemM.getAcceptNumber().equalsIgnoreCase("NULL")) {
                    itemM.setAcceptNumber(itemM.getCcusId());
                }
                if (itemM.getAcceptNumber().equals(item.getAcceptNumber())) {
                    listM.add(itemM);
                    sumMd.updateAndGet(v -> new Double((double) (v + Double.parseDouble(itemM.getMd()))));
                    sumMc.updateAndGet(v -> new Double((double) (v + Double.parseDouble(itemM.getMc()))));
                }
            });
//            if (listM.size() <= 1) {
//                return;
//            }
            double mdmcSum = sumMd.get() - sumMc.get();
            AtomicReference<Double> mdmcSumC = new AtomicReference<>((double) 0);
            if (mdmcSum < 0) {
                listM.forEach(itemC -> {
                    double mdmc = Double.parseDouble(itemC.getMd()) - Double.parseDouble(itemC.getMc());
                    if (mdmc > 0) {
                        mdmcSumC.updateAndGet(v -> new Double((double) (v + mdmc)));
                    }
                });
            }else if(mdmcSum >0){
//                return;
            }
//            else if (mdmcSum == 0)
            listM.forEach(itemC -> {
                double mdmc = Double.parseDouble(itemC.getMd()) - Double.parseDouble(itemC.getMc());
                if (mdmc == 0) {
                    return;
                }

                accvouch.setCcusId(itemC.getCcusId());
                accvouch.setCcode(itemC.getCcode());
                accvouch.setMd("0");
                accvouch.setMc("0");
                accvouch.setCdigest(itemC.getCcodeName() + "调整" + itemC.getcCusAbbName());
                accvouch.setCcodeEqual(itemC.getCcode());
                if (mdmc > 0) {
//                    if (item.getCcode().equals("21410201")) {
//                        accvouch.setCcodeEqual("51010401,2171110506");
//                    } else if (item.getCcode().equals("21410202")) {
//                        accvouch.setCcodeEqual("51010501,2171110507");
//                    }
                    accvouch.setMc(mdmc + "");
                } else {
                    if (mdmcSum < 0) {
                        if (mdmcSumC.get() == 0) {
                            return;
                        }
                        if ((mdmcSumC.get() + mdmc) < 0) {
                            accvouch.setMd(mdmcSumC.get() + "");
                            mdmcSumC.set(0.00);
                        } else {
                            accvouch.setMd(-mdmc + "");
                            mdmcSumC.updateAndGet(v -> new Double((double) (v + mdmc)));
                        }
                    } else
                        accvouch.setMd(-mdmc + "");
                }
//                inid[0]++;
                accvouch.setInid(Long.parseLong(inid.incrementAndGet() + ""));
                accvouch.setCcodeexchEqual(accvouch.getCcodeEqual());
                glAccvouchService.insertGlAccvouch(accvouch);
            });


        });
        return toAjax(ledyAccassService.insertLedyAccass(ledyAccass));
    }

    /**
     * 删除凭证现金流量
     */
    @PreAuthorize("@ss.hasPermi('erp:accass:remove')")
    @Log(title = "凭证现金流量", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ccusIds}")
    public AjaxResult remove(@PathVariable String[] ccusIds) {
        return toAjax(ledyAccassService.deleteLedyAccassByCcusIds(ccusIds));
    }
}
